var express = require("express");
var router = express.Router();
const productModel = require("../../models/productModel");
const shopCartModel = require("../../models/shopCartModel");
const charProductModel = require("../../models/characteristicProductModel");

// 获取购物车列表
router.get("/:userId", (req, res) => {
  const { userId } = req.params;
  shopCartModel
    .findOne({ userId: userId })
    .populate("items.productId")
    .populate("items.charProductId")
    .then((data) => {
      if (data.length === 0) {
        return res.json({
          code: 200,
          msg: "数据为空",
          data: data,
        });
      }
      return res.json({
        code: 200,
        msg: "获取购物车列表成功",
        data:data,
      });
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
    });
});

// 添加购物车
router.post("/", async (req, res) => {
  const { userId, productId, charProductId, quantity } = req.body;
  try {
    // 添加的是特色农产品时
    if (!productId) {
      const charProduct = await charProductModel.findById(charProductId);
      if (!charProduct) {
        return res.status(404).json({ message: "没有该农产品" });
      }
      if (quantity > charProduct.quantity) {
        return res.json({
          code: -1,
          data: null,
          msg: "库存不足！",
        });
      } else {
        let price = charProduct.price * quantity;

        let cart = await shopCartModel.findOne({ userId });

        if (!cart) {
          cart = new shopCartModel({
            userId,
            items: [{ productId, charProductId, quantity, price }],
          });
        } else {
          const existingProduct = cart.items.find((product) => {
            if (product.charProductId) {
              return product.charProductId.equals(charProductId);
            } else {
              return false;
            }
          });

          if (existingProduct) {
            existingProduct.quantity += quantity;
            existingProduct.price += price;
          } else {
            cart.items.push({
              productId: null,
              charProductId,
              quantity,
              price,
            });
          }
        }

        await cart.save();
        return res.json({
          code: 200,
          data: null,
          msg: "成功加入购物车!",
        });
      }
    } else {
      //添加的是农产品时
      const product = await productModel.findById(productId);
      if (!product) {
        return res.status(404).json({ message: "没有该农产品" });
      }
      if (quantity > product.quantity) {
        return res.json({
          code: -1,
          data: null,
          msg: "库存不足！",
        });
      } else {
        let price = product.price * quantity;

        let cart = await shopCartModel.findOne({ userId });

        if (!cart) {
          cart = new shopCartModel({
            userId,
            items: [{ productId, charProductId, quantity, price }],
          });
        } else {
          const existingProduct = cart.items.find((product) => {
            if (product.productId) {
              return product.productId.equals(productId);
            } else {
              return false;
            }
          });

          if (existingProduct) {
            existingProduct.quantity += quantity;
            existingProduct.price += price;
          } else {
            cart.items.push({
              productId,
              charProductId: null,
              quantity,
              price,
            });
          }
        }

        await cart.save();
        return res.json({
          code: 200,
          data: null,
          msg: "成功加入购物车!",
        });
      }
    }
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// 更新购物车商品数量
router.put("/", async (req, res) => {
  const { userId, productId, charProductId, count } = req.body;
  try {
    const product = await productModel.findById(productId);
    const charProduct = await charProductModel.findById(charProductId);
    const cart = await shopCartModel.findOne({ userId });

    if (!cart) {
      return res.status(404).json({ message: "没有该购物车" });
    }
    // 农产品
    if (product) {
      const existingProduct = cart.items.find((product) => {
        if (product.productId) {
          return product.productId.equals(productId);
        } else {
          return false;
        }
      });

      if (!existingProduct) {
        return res.status(404).json({ message: "购物车没有该农产品" });
      }

      existingProduct.quantity += count;
      existingProduct.price = existingProduct.quantity * product.price;

      await cart.save();
      return res.json({
        code: 200,
        msg: "修改成功",
      });
    }
    if (charProduct) {
      const existingProduct = cart.items.find((product) => {
        if (product.charProductId) {
          return product.charProductId.equals(charProductId);
        } else {
          return false;
        }
      });

      if (!existingProduct) {
        return res.status(404).json({ message: "购物车没有该农产品" });
      }

      existingProduct.quantity += count;
      existingProduct.price = existingProduct.quantity * charProduct.price;

      await cart.save();
      return res.json({
        code: 200,
        msg: "修改成功",
      });
    }
  } catch (err) {
    res.status(400).json({ message: err.message });
  }
});

// 删除购物车
router.post("/delete", async (req, res) => {
  const { userId, productIds, charProductIds } = req.body;
  try {
    let shopcart = await shopCartModel.findOne({ userId });
    if (!shopcart) {
      return res.status(404).json({ message: "未找到当前用户的购物车" });
    }
    if (productIds.length !== 0) {
      shopcart.items = shopcart.items.filter(
        (product) => !productIds.includes(product.productId?.toString())
      );
    }
    if (charProductIds.length !== 0) {
      shopcart.items = shopcart.items.filter(
        (product) => !charProductIds.includes(product.charProductId?.toString())
      );
    }
    const updatedshopCart = await shopcart.save();
    return res.json({
      code: 200,
      data: updatedshopCart,
      msg: "删除成功~",
    });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// 获取购物车价格总额
router.post("/totalPay", async (req, res) => {
  try {
    const { productIds, charProductIds } = req.body;
    if (productIds.length === 0 && charProductIds.length === 0) {
      return res.json({
        code:200,
        total: 0,
        count: 0,
      });
    }
    const cart = await shopCartModel
      .findOne({ userId: req.body.userId })
      .populate("items.productId")
      .populate("items.charProductId");
    let total = 0;
    let count = 0;

    for (const product of cart.items) {
      if (!product.charProductId) {
        if (productIds.includes(product.productId._id.toString())) {
          total += product.quantity * product.productId.price;
          count += product.quantity;
        }
      } else {
        if (charProductIds.includes(product.charProductId._id.toString())) {
          total += product.quantity * product.charProductId.price;
          count += product.quantity;
        }
      }
    }
    return res.json({
      code:200,
      total,
      count,
    });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

module.exports = router;
